package com.haiqiu.common.exception;


import com.haiqiu.common.result.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author HaiQiu
 * @date 2021/4/2 20:39
 * @desc
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 异常处理类
     * @param e 异常
     * @return ResultData
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData exception(Exception e){
        LOGGER.error((e.getMessage()));
        e.printStackTrace();
        if (e instanceof BaseException){
            return ResultData.fail(e.getMessage());
        }
        else if (e instanceof UsernameNotFoundException) {
            return ResultData.fail(e.getMessage());
        }else if (e instanceof MethodArgumentNotValidException){
            String message = ((MethodArgumentNotValidException)e).getBindingResult().getFieldErrors().get(0).getDefaultMessage();
            return ResultData.fail(message);
        }else {
            return ResultData.fail(e.getMessage());
        }

    }


}
